import http.client
import json

from flask import request
from flask_restful import Resource, fields, marshal_with, reqparse


class Ip(Resource):
    ip_fields = {
        "as": fields.String,
        "city": fields.String,
        "country": fields.String,
        "countryCode": fields.String,
        "isp": fields.String,
        "lat": fields.String,
        "lon": fields.String,
        "org": fields.String,
        "query": fields.String,
        "region": fields.String,
        "regionName": fields.String,
        "status": fields.String,
        "timezone": fields.String,
        "zip": fields.String
    }

    query_url = 'http://ip-api.com/json/'

    @marshal_with(ip_fields)
    def get(self):
        httpClient = None
        try:
            httpClient = http.client.HTTPConnection('ip-api.com')
            httpClient.request('GET', self.query_url + request.headers.environ.get('HTTP_REAL_IP'))
            # response是HTTPResponse对象
            response = httpClient.getresponse()
            jsonResponse = response.read().decode("utf-8")
            dictResponse = json.loads(jsonResponse)  # 获得返回的结果，结果为dict格式
            data = dict(dictResponse)
            return data, 200
        except Exception as e:
            print(e)
        finally:
            if httpClient:
                httpClient.close()

    @marshal_with(ip_fields)
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('ip', type=str)
        args = parser.parse_args()
        ip = args['ip']
        httpClient = None
        try:
            httpClient = http.client.HTTPConnection('ip-api.com')
            httpClient.request('GET', self.query_url + ip)
            # response是HTTPResponse对象
            response = httpClient.getresponse()
            jsonResponse = response.read().decode("utf-8")
            dictResponse = json.loads(jsonResponse)  # 获得返回的结果，结果为dict格式
            data = dict(dictResponse)
            return data, 200
        except Exception as e:
            print(e)
        finally:
            if httpClient:
                httpClient.close()
